import router, { addPermissionRoute } from './index'
import { useUserStore } from '@/stores/user';

const whiteList = ['/login']; // no redirect whitelist

router.beforeEach(
  (to, from, next) => {
    const userStore = useUserStore();
    if (whiteList.includes(to.path)) {
      // 在免登录白名单，直接进入
      next();
    } else {
      // 用户是否登录过
      if (userStore.token) {
        // 用户数据是否已获取
        if (userStore.routesLoaded) {
          next();
        } else {
          userStore.getPermissions().then(() => {
            // 获取权限列表
            // 生成路由
            addPermissionRoute(userStore.permissionList)
            userStore.setRoutesLoaded(true)
            next({ ...to, replace: true })
          }).catch((e) => {
            console.error(e);
            next(`/login`);
          })
        }
      } else {
        next(`/login`); // 否则全部重定向到登录页
      }
    }
  }
)